﻿#if UNITY_EDITOR

using UnityEngine;
using UnityEditor;
using UnityEditor.Tilemaps;
using Memo.Electricity.Game;
using System.Linq;

namespace Memo.Electricity.Editor
{
	[CustomGridBrush(true, false, false, "OrderBlockBrush")]
	public class OrderBlockBrush : BasePrefabBrush
	{
		[SerializeField] private int mEditorNextOrder = 0;

		public override void Paint(GridLayout grid, GameObject brushTarget, Vector3Int position)
		{
			base.Paint(grid, brushTarget, position);

			CBaseOrderBlockMgr mgr = brushTarget.GetComponent<CBaseOrderBlockMgr>();
			if (mgr == null)
			{
				Debug.Log("brushTarget必须为OrderBlockMgr");
				return;
			}
			GameObject template = brushTarget.GetComponent<CBaseOrderBlockMgr>().Tempalte;

			var objectsInCell = GetObjectsInCell(grid, brushTarget.transform, position);
			var existPrefabObjectInCell = objectsInCell.Any(objectInCell =>
				PrefabUtility.GetCorrespondingObjectFromSource(objectInCell) == template);

			if (!existPrefabObjectInCell)
			{
				base.InstantiatePrefabInCell(grid, brushTarget, position, template, Quaternion.identity);
			}

		}

		protected override void OnPostPaint(GameObject instance, GameObject brushTarget)
		{
			CBaseOrderBlock block = instance.GetComponent<CBaseOrderBlock>();
			block.Init();

			if (block == null)
			{
				Debug.LogError("prefab必须为OrderBlock");
				DestroyImmediate(instance);
				return;
			}

			block.Order = mEditorNextOrder++;

		}

	}

}



#endif